//
//  GasStationVC.m
//  NtoccDriverNew
//
//  Created by niyongsheng on 2022/10/17.
//  Copyright © 2022 GCY. All rights reserved.
//

#import "GasStationVC.h"
#import "GasStationModel.h"
#import "GasStationCell.h"
#import "CYCityChooseView.h"
#import "NYSTitleButton.h"
#import "QDLocationManager.h"

@interface GasStationVC ()
<
UITableViewDelegate,
UITableViewDataSource,
CYChooseRegionDelegate
>
{
    NSInteger _pageNum;
    NSString *_keyword;
    
    NSString *_address;
    NSString *_provinceId;
    NSString *_cityCompId;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSourceMArr;

@property (weak, nonatomic) IBOutlet UIView *searchView;
@property (weak, nonatomic) IBOutlet UITextField *searchTF;

@property (strong, nonatomic) NYSTitleButton *rightBtn;
@end

@implementation GasStationVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.navigationItem.title = @"油站列表";
    self.tabBarController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    ViewRadius(_searchView, 5)
    [self.view addSubview:self.tableView];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - CYChooseRegionDelegate
- (void)getAllInfoProvinceCode:(NSString *)provinceCode provinceName:(NSString *)provinceName cityCode:(NSString *)cityCode cityName:(NSString *)cityName countyCode:(NSString *)countyCode countyName:(NSString *)countyName {
    
//    _address = CJStringWithFormat(@"%@%@%@",provinceName,cityName,countyName);
    _provinceId = [provinceCode isNotBlank] ? provinceCode : nil;
    _cityCompId = [cityCode isNotBlank] ? cityCode : nil;
    
    if ([cityName isNotBlank]) {
        _address = cityName;
    } else {
        if ([provinceName isEqualToString:@"重置"] || [provinceName isEqualToString:@"全国"]) {
            _address = @"";
        } else {
            _address = provinceName;
        }
    }
    
    _address = [self replaceStr:_address byStr:@"省"];
    _address = [self replaceStr:_address byStr:@"市"];
    _address = [self replaceStr:_address byStr:@"自治区"];
    
    [self.rightBtn setTitle:[_address isNotBlank] ? _address : @"地区" forState:UIControlStateNormal];
    
    [self.tableView.mj_header beginRefreshing];
}

- (NSString *)replaceStr:(NSString *)str byStr:(NSString *)byStr {
    NSMutableString *strm = [NSMutableString stringWithString:str];
    [strm replaceOccurrencesOfString:byStr
                          withString:@""
                             options:NSLiteralSearch
                               range:NSMakeRange(0, strm.length)];
    
    return [NSString stringWithString:strm];
}

- (IBAction)searchBtnOnclicked:(UIButton *)sender {
    [self.view endEditing:YES];
    
    _keyword = _searchTF.text;
    [self.tableView.mj_header beginRefreshing];
}

/// 刷新
/// @param isHeader 是否下拉刷新
- (void)refreshing:(BOOL)isHeader {
    @weakify(self)
    QDLocationManager *location = [[QDLocationManager alloc] init];
    location.locationCompletionBlock = ^(NSString * _Nonnull address, NSString * _Nonnull latitude, NSString * _Nonnull longitude, NSError * _Nonnull error) {
        if (error) {
            [XSInfoView showInfo:error.description onView:self.view];
            return;
        }
        
        if (isHeader) {
            _pageNum  = 1;
        } else {
            _pageNum ++;
        }
        NSString *urlStr = CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],GasStationInfo);
        NSMutableDictionary *params = @{
            @"pageNum" : @(_pageNum),
            @"pageSize" : @10,
            @"stationName" : _keyword
        }.mutableCopy;
        NSString *origins = [NSString stringWithFormat:@"%@,%@", longitude, latitude];
        [params setValue:origins forKey:@"origins"];
        [params setValue:_address forKey:@"address"];
    //    [params setValue:_provinceId forKey:@"provinceId"];
    //    [params setValue:_cityCompId forKey:@"cityCompId"];
        
        
        [HTTPManager getNetworkRequest:urlStr
                         withParameter:params
                                withVC:self
                               netName:@"油站列表"
                               success:^(id response, NSString *msg) {
            @strongify(self)
            if (isHeader) {
                self.dataSourceMArr = [GasStationModel mj_objectArrayWithKeyValuesArray:response[@"records"]];
                [self.tableView.mj_footer resetNoMoreData];
                [self.tableView.mj_header endRefreshing];
                [self.tableView reloadData];
                
            } else {
                NSArray *dictArr = response[@"records"];
                if (dictArr.count > 0) {
                    [self.dataSourceMArr addObjectsFromArray:[GasStationModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView reloadData];
                    
                } else {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
        } failure:^(NSInteger code, NSString *msg) {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }];
    };
    [location reGeocodeAction];
}

#pragma mark - TableView 代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceMArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellReuseIdentifier = @"GasStationCell";
    GasStationCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataSourceMArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    GasStationModel *model = self.dataSourceMArr[indexPath.row];
    [self tapNavActionWithAddress:model.address coordinate:(CLLocationCoordinate2D){model.txPosy, model.txPosx}];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, ScreenW, ScreenH - MenuBarHeight - NavHeight - 50) style:UITableViewStylePlain];
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([GasStationCell class]) bundle:nil];
        [_tableView registerNib:nib forCellReuseIdentifier:NSStringFromClass([GasStationCell class])];
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        @weakify(self)
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            @strongify(self)
            [self refreshing:YES];
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self refreshing:NO];
        }];
        
        _tableView.mj_header = header;
        _tableView.mj_footer = footer;
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NYSTitleButton *)rightBtn {
    if (!_rightBtn) {
        @weakify(self)
        UIImage *riconImg = [[UIImage imageNamed:@"gcy_icon_oil_arrow_gray"] imageChangeColor:Theme_ColorValue];
        _rightBtn = [NYSTitleButton buttonWithType:UIButtonTypeCustom];
        [_rightBtn setTitleColor:Theme_ColorValue forState:UIControlStateNormal];
        [_rightBtn setTitle:@"地区" forState:UIControlStateNormal];
        _rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _rightBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
        _rightBtn.frame = CGRectMake(0, 0, 60, 44);
        [_rightBtn setImage:riconImg forState:UIControlStateNormal];
        [_rightBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
            @strongify(self)
            [CYCityChooseView shared].delegate = self;
            [CYCityChooseView shared].pageShowFlag = 0;
            [CYCityChooseView shared].isTwoLevel = YES;
            [[CYCityChooseView shared] show];
        }];
    }
    return _rightBtn;
}

#pragma mark - 根据已安装的app和经纬度跳地图导航
- (void)tapNavActionWithAddress:(NSString *)address coordinate:(CLLocationCoordinate2D)coordinate {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择导航" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"苹果自带地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
        
        MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        MKMapItem *tolocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
        
        tolocation.name= address;
        
        [MKMapItem openMapsWithItems:@[currentLocation,tolocation]launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving, MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
    }];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        UIAlertAction*action2 = [UIAlertAction actionWithTitle:@"高德地图"style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
            
            NSString *urlsting =[[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &backScheme= &lat=%f&lon=%f&dev=0&style=2",coordinate.latitude, coordinate.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlsting] options:@{UIApplicationOpenURLOptionsSourceApplicationKey: @YES} completionHandler:nil];
            
        }];
        
        [alert addAction:action2];
    }
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"百度地图"style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
            NSString *urlsting =[[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=gcj02", coordinate.latitude, coordinate.longitude, address] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlsting] options:@{UIApplicationOpenURLOptionsSourceApplicationKey: @YES} completionHandler:nil];
            
        }];
        [alert addAction:action3];
        
    }
    
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    
    [alert addAction:action4];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

@end
